package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.constant.RedMoney;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppUserRewardSetupMapper;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.taobao.OrderController;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.OrderNewScheme;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo;
import com.eco.fanliapp.vo.TbkOrderGetInfo;
import com.eco.fanliapp.vo.TbkOrderGetInfo.NTbkOrderDataBean;
import com.eco.fanliapp.vo.job.*;
import com.eco.fanliapp.vo.respone.DTKResponse;
import com.google.common.base.Joiner;
import com.qiniu.util.Json;
import com.taobao.api.response.TbkRelationRefundResponse;
import com.taobao.api.response.TbkScOrderDetailsGetResponse;
import com.taobao.api.response.TbkScPunishOrderGetResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TaoBaoOrderServiceImpl implements ITaoBaoOrderService {


    @SuppressWarnings({"unused", "rawtypes"})
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IAppOrderDetailService iAppOrderDetailService;
    @Autowired
    private IUserCashschemeService userCashschemeService;
    @Autowired
    private IAppUserOrderService iAppUserOrderService;
    @Autowired
    private IAppNewsLogService iAppNewsLogService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IGoodsFreeService iGoodsFreeService;
    @Autowired
    private ICommissionFreezeService iCommissionFreezeService;
    @Autowired
    private IGoodsFreeService goodsFreeService;
    @Autowired
    private IAppUserRedRewardService IAppUserRedRewardService;
    @Autowired
    private Environment environment;
    @Autowired
    private OrderController orderController;
    @Autowired
    private ITaoBaoService taobaoService;

    @Autowired
    private IAppGoodsService iAppGoodsService;

    @Autowired
    private IAppUserSearchHistoryService appUserSearchHistoryService;

    @Autowired
    private ISyUserTaskService iSyUserTaskService;

    @Autowired
    private ISyTaskTypeService iSyTaskTypeService;

    @Autowired
    private ISyUserMoneyService iSyUserMoneyService;

    @Autowired
    private IAppWxWithdrawalService iAppWxWithdrawalService;

    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private FindItemIdUtils taoBaoUtils;

    @Autowired
    private UpdateUserCommon updateUserCommon;

    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;

    @Autowired
    private ISySwitchService iSySwitchService;

    @Autowired
    private IAppUserRewardSetupService iAppUserRewardSetupService;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;
    @Autowired
    private ISyChannelGoodsService syChannelGoodsService;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IAppOrderDetailService appOrderDetailService;
    @Autowired
    private ICommissionFreezeService commissionFreezeService;

    @Autowired
    private RedisTemplateService redisTemplateService;
    /**
     * Eco API
     * 拉取付款订单
     *
     * @param session        淘客的授\权session来查订单
     * @param startTime      下单时间
     * @param pageNo         第几页 默认1，1~100
     * @param tkStatus       订单状态1: 全部订单，3：订单结算，12：订单付款， 13：订单失效，14：订单成功； 订单查询类型为‘结算时间’时，只能查订单结算状态
     * @param orderCountType 订单数据统计类型，1: 2方订单，2: 3方订单，如果不设置，或者设置为1，表示2方订单
     * @param orderQueryType 订单查询类型，创建时间“create_time”，或结算时间“settle_time”。当查询渠道或会员运营订单时，建议入参创建时间“create_time”进行查询
     * @param orderScene     订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，默认为1，通过设置订单场景类型，媒体可以查询指定场景下的订单信息，例如不设置，或者设置为1，表示查询常规订单，常规订单包含淘宝客所有的订单数据，含渠道，及会员运营订单，但不包含3方分成，及维权订单
     * @return https://open.taobao.com/api.htm?docId=38078&docType=2
     */
    @Override
    @Async("myTaskAsyncPool")
    public void getPayOrderDetail(String session, String startTime, String endTime, long pageNo,long tkStatus, long orderCountType,
                                  String orderQueryType, long orderScene,int type,String positionIndex) {
        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000L * 8;

        try {

            // TODO Auto-generated method getPayOrderDetail获取渠道的付款订单
//            String str = OrderMain(session, startTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene);


            String str = OrderMainNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene, positionIndex);
            //获取锁来打印日志
            if (redisLockService.lock("getPayOrderDetail" + "doOrderDetailFromTBK", (System.currentTimeMillis() + 1000L * 60L * 19L) + "")) {
                log.info("获取到付款数据：{}", str);
            } else if (type == 1 || pageNo > 1) {
                log.info("获取到付款数据：{}", str);
            }

            TbkScOrderDetailsGetResponse info = JsonUtils.getJsonToBean(str, TbkScOrderDetailsGetResponse.class);

            if (info.isSuccess() && info != null && info.getData() != null && info.getData().getResults() != null && info.getData().getResults().size() > 0) {
                //#####位点，除第一页之外，都需要传递；前端原样返回。#####
                positionIndex = info.getData().getPositionIndex();

                for (TbkScOrderDetailsGetResponse.PublisherOrderDto order : info.getData().getResults()) {

                    AppUser appUser = UserMainNew(order);//关联用户
                    if(StringUtils.isEmpty(appUser)) {
                        log.info("付款订单关联不到用户,order={}itemId={}relationID={}", order.getTradeId(),order.getItemId(),order.getRelationId());
                        continue;
                    }

                    AppOrderDetail appOrderDetail = OrderDteailMainNew(order, appUser);

                    //获取锁
                    if (!redisLockService.lock(order.getTradeId() + "doOrderDetailFromTBK", startTimes + "")) {
                        continue;
                    }

                    //数据库中查询该订单
                    AppOrderDetail appOrderDetailDatabase = iAppOrderDetailService.selectAppOrderDetailByTradeId(Long.parseLong(order.getTradeId()));

                    int i = 0;
                    int i1 = 0;
                    int status = 0;//免单商品状态

                    //查询商品
                    AppGoods appGoods = getAppgoods(order.getItemId().toString(), appOrderDetail);


                    GoodsFree goodsFree = null;
                    if (appOrderDetailDatabase == null || appOrderDetailDatabase.getTradeId() == null) {

                        //查询免单商品信息
                        goodsFree = iGoodsFreeService.selectByGoodsId(order.getItemId());
                        ServerResponse<String> serverResponse = goodsFreeService.checkHaveBuy(appUser == null ? 0 : appUser.getUserId(), 1);
                        status = serverResponse.getStatus();
                        //如果是用户首单并且免单商品，记录免单状态
                        if (goodsFree != null && status == 515 && appUser != null && goodsFree.getNumber() > 0) {
                            appOrderDetail.setGoodFrees(1L);
                        } else {
                            appOrderDetail.setGoodFrees(0L);
                        }

                        //设置商品的图片
                        appOrderDetail.setItemPic(appGoods == null ? "" : appGoods.getItempic());

                        try {
                            usetTask(appUser, Long.parseLong(order.getTradeId()),appOrderDetail.getTbPaidTime());//根据用户传入日期处理红包任务
                        } catch (Exception e) {
                            log.info("====每日首购任务异常===={}user={}orderId={}", e.getMessage(), appUser.getUserId(), order.getTradeId());
                        }
                        //redis获取订单来源
                        String s = addBuySource(appUser.getUserId(), order.getItemId());
                        appOrderDetail.setBuySource(s);
                        i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
                        if (i > 0) {
                            log.info("付款订单{}入库成功", order.getTradeId());
                        }
                        if (i > 0 && appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1) {
                            //将订单次数加一的同时库存减一,将免单商品减去1
                            i1 = iGoodsFreeService.updateTotalOrdersByGoodsId(goodsFree.getId());
                            log.info("付款订单{}入库成功免单商品减一--i1={}", order.getTradeId(), i1);
                        }
                    } else {
                        appOrderDetail.setBinding(appOrderDetailDatabase.getBinding());
                        appOrderDetail.setBindingTime(appOrderDetailDatabase.getBindingTime());
                        appOrderDetail.setDeleted(appOrderDetailDatabase.getDeleted());
                        appOrderDetail.setTableCreateTime(appOrderDetailDatabase.getTableCreateTime());
                        appOrderDetail.setGoodFrees(appOrderDetailDatabase.getGoodFrees());
                        appOrderDetail.setItemPic(appOrderDetailDatabase.getItemPic());
                        appOrderDetail.setFanliMoney(appOrderDetailDatabase.getFanliMoney());
                        if (appOrderDetail.getItemPic() == null) {
                            appOrderDetail.setItemPic("http:" + appOrderDetail.getItemImg());
                        }
                        if (appOrderDetailDatabase.getItemPic() == null || "".equals(appOrderDetailDatabase.getItemPic())
                                || appOrderDetailDatabase.getItemImg() == null || "".equals(appOrderDetailDatabase.getItemImg())
                                ) {
                            //redis获取订单来源
                            String s = addBuySource(appUser.getUserId(), order.getItemId());
                            appOrderDetail.setBuySource(s);
                            i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
                            if (i > 0) {
                                i = 2;
                            }
                        }
                        //订单数据库已经存在
                        //判断是否是预售订单，金额是否有变动
                        i = judgePreparePayOrder(appOrderDetail, appOrderDetailDatabase);
                    }

                    //插入成功
                    if (i > 0) {
                        List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));

                        //订单金额变动，第二次处理预售订单
                        if (i == 3 && !CollectionUtils.isEmpty(userOrders)) {
                            handlePreparePayOrder(appUser, appGoods, appOrderDetail, userOrders, true);
                            continue;
                        }

                        //如果是维权订单就不处理了。
                        if (i == 2 && userOrders != null && userOrders.size() > 0 && userOrders.get(0) != null && userOrders.get(0).getOrderSettleStatus() != null && userOrders.get(0).getOrderSettleStatus() == 3) {
                            continue;
                        }
                        if (!CollectionUtils.isEmpty(userOrders)) {
                            log.info("付款订单{}已经处理了", order.getTradeId());
                        } else {
                            //判断订单是不是免单，免单不算首购红包
                            if( appOrderDetail.getGoodFrees() != 1){
                                //首购红包绑定
                                firstPurchaseRedPacket(appUser.getUserId(),order.getItemId(),Long.parseLong(order.getTradeId()));
                            }


                            //是否给予上级6元奖励（zc）
                            try {
                                log.info("=========开始执行上级6元红包的问题==========--userId={}--orderId={}", appUser.getUserId(), order.getTradeId());
                                IAppUserRedRewardService.addInvitationedMoney(appUser, appOrderDetail);
                                log.info("=========结束执行6元红包的问题===========--userId={}--orderId={}", appUser.getUserId(), order.getTradeId());
                            } catch (Exception e) {
                                log.error("是否给予上级6元奖励方法报错--userId={}--orderId={}", appUser.getUserId(), order.getTradeId());
                                e.printStackTrace();
                            }

                            //免单商品处理
                            boolean isGoGoodFree = goFreeGoods(goodsFree, appUser, appOrderDetail, appGoods, status);
                            if (!isGoGoodFree) {//是否走免单
                                //非免单商品//走正常分佣
                                boolean isGoSchema = goSchema(appUser, appOrderDetail, appGoods);
                            }
                        }

                    } else {
                        log.error("订单{}入库失败{}", order.getTradeId(), new Throwable().getStackTrace());
                    }
                }
                if (info.getData().getHasNext()) {
                    getPayOrderDetail(
                            session, startTime, endTime, pageNo + 1, tkStatus,
                            orderCountType, orderQueryType, orderScene, type ,positionIndex);
                }
                //for循环结束
//                return ServerResponse.createBySuccess("数据获取成功", info.getData().getResults());
            } else {
                return ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (type == 0) {
                this.countLauncherPay.countDown();
            }

        }
        return ;
    }
    //判断是否是首单，绑定首单红包，免单不算首单
    public void firstPurchaseRedPacket(Long userId,Long itemId,Long tradeId){
        //判断用户是否有任务红包
        //首次绑定订单，修改新人任务红包状态
        QueryWrapper<AppUserRedReward> queryWrapper = new QueryWrapper<AppUserRedReward>();
        queryWrapper.eq("user_id", userId).eq("hb_type", 3).eq("hb_status", 1);
        AppUserRedReward appUserRedReward = IAppUserRedRewardService.getOne(queryWrapper);
        AppUserRewardSetup appUserRewardSetup = null;
        if (redisTemplateService.hasKey("AppUserRewardSetup")) {
            appUserRewardSetup = redisTemplateService.getTByKey("AppUserRewardSetup",AppUserRewardSetup.class);
        } else {
            appUserRewardSetup = iAppUserRewardSetupService.getById(1);
            redisTemplateService.set("AppUserRewardSetup", appUserRewardSetup, 60*60);
        }
        //任务红包没有起用过并且当前时间小于红包使用期限
        if (appUserRedReward != null && appUserRedReward.getHbStatus() == 1 && appUserRedReward.getOrderId() == null
                && ((System.currentTimeMillis() - appUserRedReward.getCreateTime()) < appUserRewardSetup.getTaskRedMoneyInvalidTime() * 24L * 60 * 60 * 1000L)) {

            QueryWrapper<AppUserSearchHistory> searchHistoryQueryWrapper = new QueryWrapper<AppUserSearchHistory>();
            searchHistoryQueryWrapper.eq("user_id", userId).eq("item_id", itemId);

            //如果搜索过该商品
            int count = appUserSearchHistoryService.count(searchHistoryQueryWrapper);
            if (count > 0) {
                AppUserRedReward appUserRedRewardNew = new AppUserRedReward();
                appUserRedRewardNew.setTableId(appUserRedReward.getTableId());
                appUserRedRewardNew.setHbStatus(7);
                appUserRedRewardNew.setOrderId(tradeId);
                IAppUserRedRewardService.updateById(appUserRedRewardNew);
                //增加或修改日志状态
                int j = updateUserCommon.UpdateUserTaskStatus(appUserRedReward.getUserId(), 3);
                if (j > 0) {
                    log.info("首购任务修改状态成功--------userId={}--orderId={}", userId, tradeId);
                } else {
                    log.info("首购任务修改状态失败--------userId={}--orderId={}", userId, tradeId);
                }
            }
        }

    }

    public boolean goSchema(AppUser appUser, AppOrderDetail appOrderDetail, AppGoods appGoods) {

        //拿到用户佣金比例和用户返佣信息
        OrderNewScheme orderNewScheme = handleCustomerMoney(appUser, appOrderDetail);

        Integer orderScale = orderNewScheme.getOrderScale();//下单用户佣金比例
        Integer parentScale = orderNewScheme.getParentScale();//上级佣金比例
        Integer twoParentScale = orderNewScheme.getTwoParentScale();//上上级佣金比例
        //获取用户杀熟佣金比例
        BigDecimal customerMoney = orderNewScheme.getCustomerMoney();
        CommissionFreeze commissionFreeze = commissionFreezeService.selectByPrimaryKey(2, 1);

        AppUserOrder appUserOrder = new AppUserOrder();
        appUserOrder.setOrderId(appOrderDetail.getTradeId());
        appUserOrder.setOrderStatus(12);
        appUserOrder.setOrderSettleStatus(1);

        appUserOrder.setUserId(appUser.getUserId());
        appUserOrder.setTaobaoUserId(Long.valueOf(appUser.getTaobaoUserId() == null ? 0L : appUser.getTaobaoUserId()));
        appUserOrder.setOrderGrade(1);
        appUserOrder.setCommission(customerMoney.
                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney));
        appUserOrder.setSpareMoney((customerMoney.
                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney)).add(BigDecimalUtils.Format(appGoods == null ? 0d : appGoods.getCouponmoney())));
        //正常分佣冻结时间
        appUserOrder.setFreezeDay(commissionFreeze.getDelaydays());
        int i2 = iAppUserOrderService.insertAppUserOrder(appUserOrder);
        log.info("插入用户订单中间表数据是否成功{},：用户id：{}:订单{}: {}", i2, appUser.getUserId(), appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
        if (i2 > 0) {
            if (appOrderDetail.getTkStatus() != 13) {
                try {
                    iAppNewsLogService.newsType(appUser.getUserId(),
                            NewsEnumLog.NEWS_ORDER_PAY.getNewsType(),
//                                            appUserOrder.getCommission(), (appUserOrder.getCommission().add(new BigDecimal(appGoods == null ? "0" : appGoods.getCouponmoney() + ""))).toString());
                            appUserOrder.getCommission(), appGoods == null ? "" : appGoods.getItemshorttitle(), (appUserOrder.getCommission().add(new BigDecimal(appGoods == null ? "0" : appGoods.getCouponmoney() + ""))).toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("付款订单{}入关联库成功发消息异常:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
                } finally {
                    log.info("付款订单{}入关联库成功:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
                }
            }

        } else {
            log.error("付款订单{}入关联库失败:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
        }
        //查询1级上级
        AppUser parentAppUser = iAppUserService.selectSuperUserInfoBySuperInviteCode(appUser.getSuperInviteCode());
        if (parentAppUser != null) {
            if (parentScale != null && parentScale > 0) {

                AppUserOrder appUserOrderParent = new AppUserOrder();
                appUserOrderParent.setOrderId(appOrderDetail.getTradeId());
                appUserOrderParent.setOrderStatus(12);
                appUserOrderParent.setOrderSettleStatus(1);

                appUserOrderParent.setUserId(parentAppUser.getUserId());
                appUserOrderParent.setTaobaoUserId(Long.valueOf(appUser.getTaobaoUserId() == null ? 0L : appUser.getTaobaoUserId()));
                appUserOrderParent.setOrderGrade(2);
                appUserOrderParent.setCommission(BigDecimalUtils.FanliMoney(String.valueOf(parentScale),
                        BigDecimalUtils.Format(customerMoney)).
                        compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                        BigDecimal.valueOf(0.01) : BigDecimalUtils.FanliMoney(String.valueOf(parentScale),
                        BigDecimalUtils.Format(customerMoney)));
                appUserOrderParent.setSpareMoney(appUserOrder.getSpareMoney());

                int i3 = iAppUserOrderService.insertAppUserOrder(appUserOrderParent);
                if (i3 > 0) {
                    if (appOrderDetail.getTkStatus() != 13) {
                        try {
                            iAppNewsLogService.newsType(parentAppUser.getUserId(),
                                    NewsEnumLog.NEWS_ORDER_SUPER_PAY.getNewsType(),
                                    appUserOrderParent.getCommission(), appUserOrderParent.getCommission().toString());
                            // TODO: 粉丝下单成功公众号提醒
                            //下单成功公众号提示
                            //ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser,"30002",appOrderDetail.getItemTitle() ,appOrderDetail.getTradeId().toString(), appOrderDetail.getTbPaidTime(),appUserOrder.getCommission().toString());
                            //log.info("公众号发消息返回结果{}", JSONObject.toJSONString(result));
//                            this.weCheatMessage(appUser, "3004", appUserOrderParent.getCommission().toString());
//                            log.info("付款订单{}一级分佣成功{}:status{}", i3, appOrderDetail.getTkStatus(), appOrderDetail.getTkStatus());
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.info("付款订单{}一级分佣成功:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
                        } finally {
                            log.info("付款订单{}一级分佣成功:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
                        }
                    }
                } else {
                    log.error("付款订单{}一级分佣失败:status{}", i3, appOrderDetail.getTkStatus());
                }
            }
        }
        return true;
    }

    /**
     * 免单商品走免单
     *
     * @param goodsFree
     * @param appUser
     * @param appOrderDetail
     * @param appGoods
     * @param status
     * @return
     */
    public boolean goFreeGoods(GoodsFree goodsFree, AppUser appUser, AppOrderDetail appOrderDetail, AppGoods appGoods, int status) {

        int i2 = 0;//数据库是否添加成功
        String logTitle = "付款";
        if (appOrderDetail.getTkStatus() == 12) {
            logTitle = "付款";
        }else if (appOrderDetail.getTkStatus() == 13) {
            logTitle = "失效";
        }else if (appOrderDetail.getTkStatus() == 3) {
            logTitle = "结算";
        }else if (appOrderDetail.getTkStatus() == 14) {
            logTitle = "完成";
        }

        //查询是否是免单库的商品如果是就总订单数加1
        if (goodsFree != null && status == 515 && appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1) {

            log.info("获取到{}免单商品orderId={}--goodfreeId={}", logTitle, appOrderDetail.getTradeId(), goodsFree.getGoodsId());

            try {

                AppUserOrder appUserOrder = new AppUserOrder();
                appUserOrder.setOrderId(appOrderDetail.getTradeId());
                appUserOrder.setOrderStatus(12);
                appUserOrder.setOrderSettleStatus(1);
                appUserOrder.setOrderGrade(1);
                appUserOrder.setSpareMoney(BigDecimalUtils.Format(goodsFree.getFixedAmount()).add(BigDecimalUtils.Format(appGoods == null ? 0d : appGoods.getCouponmoney())));
                appUserOrder.setUserId(appUser.getUserId());
                appUserOrder.setTaobaoUserId(Long.valueOf(appUser.getTaobaoUserId()));
                appUserOrder.setCommission(BigDecimalUtils.Format(goodsFree.getFixedAmount()));
                //免单商品冻结10天
                appUserOrder.setFreezeDay(8);
                i2 = iAppUserOrderService.insertAppUserOrder(appUserOrder);
                //免单增加商品
                if (i2 > 0) {
                    BigDecimal bigDecimal = new BigDecimal("0");
                    if (!StringUtils.isEmpty(appGoods)) {
                        bigDecimal = new BigDecimal(appGoods.getCouponmoney()).add(new BigDecimal(appOrderDetail.getAlipayTotalPrice() == null ? "0" : appOrderDetail.getAlipayTotalPrice()));
                    }
                    iAppNewsLogService.newsType(appUser.getUserId(),
                            NewsEnumLog.NEWS_ORDER_PAY.getNewsType(),
                            BigDecimalUtils.Format(goodsFree.getFixedAmount()), goodsFree.getGoodsTitle(), BigDecimalUtils.Format(bigDecimal).toString());
                    // TODO: 下单成公众号提醒
                    //ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser,"30002",appOrderDetail.getItemTitle() ,appOrderDetail.getTradeId().toString(), appOrderDetail.getTbPaidTime(),appUserOrder.getCommission().toString());
                    //log.info("公众号发消息返回结果{}", JSONObject.toJSONString(result));
                    //this.weCheatMessage(appUser, "3002", BigDecimalUtils.Format(bigDecimal).toString());
                    log.info("{}库付款订单{}入关联库成功", logTitle, appOrderDetail.getTradeId());
                } else {
                    log.error("{}库付款订单{}入关联库失败", logTitle, appOrderDetail.getTradeId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (i2 > 0) {
            return true;
        }
        return false;
    }


    /**
     * 获取商品信息
     * @param itemId
     * @param order
     * @return
     */
    public AppGoods getAppgoods(String itemId, AppOrderDetail order) {

        AppGoods appGoods = null;
        try {
            appGoods = iAppGoodsService.findAppGoodsByItemId(itemId);
            if (appGoods == null) {
                HaoDanKuItemInfo haoDanKuItemInfo = taoBaoUtils.getHaoDanKuItemId(itemId);
                log.info("拉取商品不存在去好单库拉取商品结果{}--{}", order.getTradeId(), haoDanKuItemInfo == null ? null : haoDanKuItemInfo.getCode());
                if (haoDanKuItemInfo != null && haoDanKuItemInfo.getCode() == 1 && haoDanKuItemInfo.getData() != null) {
                    appGoods = new AppGoods();
                    HaoDanKuItemInfo.DataBean data = haoDanKuItemInfo.getData();
                    appGoods.setItempic(data.getItempic());
                    appGoods.setItemtitle(data.getItemshorttitle());
                    appGoods.setItemshorttitle(data.getItemshorttitle());
                    appGoods.setCouponmoney(Double.valueOf(data.getCouponmoney() == null ? "0" : data.getCouponmoney()));
                } else {
                    DTKResponse dtkResponse = daTaoKeItemInfoService.itemInfoByItemId(itemId);
                    log.info("拉取商品不存在去大淘客拉取商品结果{}--{}", order.getTradeId(), dtkResponse == null ? null : dtkResponse.getCode());
                    if (dtkResponse != null && dtkResponse.getCode() == 1 && dtkResponse.getData() != null) {
                        DTKResponse.DataBean data = dtkResponse.getData();
                        appGoods = new AppGoods();
                        appGoods.setItempic(data.getMainPic());
                        appGoods.setItemtitle(data.getDtitle());
                        appGoods.setItemshorttitle(data.getDtitle());
                        appGoods.setCouponmoney(Double.valueOf(data.getCouponPrice() == null ? "0" : data.getCouponPrice()));
                    }
                }
                if (appGoods == null) {
                    try {
                        ServerResponse<List<TbkItemInfoGetInfo.NTbkItem>> response = taobaoService.getSearchItemIdDetail(itemId);
                        if (response != null && response.getStatus() == 200) {
                            for (TbkItemInfoGetInfo.NTbkItem item : response.getData()) {
                                appGoods = new AppGoods();
                                appGoods.setItempic(item.getPictUrl());
//                            appGoods.setItemshorttitle();
//                            appGoods.setCouponmoney();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
            if (appGoods == null) {
                appGoods = new AppGoods();
            }
            if (com.eco.fanliapp.utils.StringUtils.isNull(appGoods.getItempic())) {
                appGoods.setItempic("http:"+order.getItemImg());
            }
            if (com.eco.fanliapp.utils.StringUtils.isNull(appGoods.getItemtitle())) {
                appGoods.setItemtitle(order.getItemTitle());
                appGoods.setItemshorttitle(order.getItemTitle());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("查询商品报错itmeid={}orderId={}", itemId, order.getTradeId());
        }

        return appGoods;

    }




    /**
     * 判断是否是预售订单并且金额不正确
     *
     * @param appOrderDetail
     * @param appOrderDetailDatabase
     */
    public int judgePreparePayOrder(AppOrderDetail appOrderDetail, AppOrderDetail appOrderDetailDatabase) {

        int i = 2;
        appOrderDetail.setGoodFrees(appOrderDetailDatabase.getGoodFrees());
        appOrderDetail.setItemPic(appOrderDetailDatabase.getItemPic());
        appOrderDetail.setFanliMoney(appOrderDetailDatabase.getFanliMoney());
        if (appOrderDetail.getItemPic() == null) {
            appOrderDetail.setItemPic("http:" + appOrderDetail.getItemImg());
        }
        i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);//重新插入

        try {
            if (//判断是预售订单
                    com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderDetail.getTbDepositTime())
                            && com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderDetail.getTkDepositTime())
                            && !"--".equals(appOrderDetail.getTkDepositTime())
                            && !"--".equals(appOrderDetail.getTbDepositTime())
                            && com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderDetail.getDepositPrice())

                    ) {

                //判断是预售订单并且本次查询订单金额大于
                if (
                        new BigDecimal(appOrderDetail.getAlipayTotalPrice()).compareTo(new BigDecimal(appOrderDetailDatabase.getAlipayTotalPrice())) > 0
                                ||
                                new BigDecimal(appOrderDetail.getPubSharePreFee()).compareTo(new BigDecimal(appOrderDetailDatabase.getPubSharePreFee())) > 0
                                ||
                                (com.eco.fanliapp.utils.StringUtils.isNull(appOrderDetailDatabase.getPayPrice()) && com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderDetail.getPayPrice()))
                        ) {

//                    appOrderDetail.setGoodFrees(appOrderDetailDatabase.getGoodFrees());
//                    appOrderDetail.setItemPic(appOrderDetailDatabase.getItemPic());
//                    appOrderDetail.setFanliMoney(appOrderDetailDatabase.getFanliMoney());
//                    if (appOrderDetail.getItemPic() == null) {
//                        appOrderDetail.setItemPic("http:" + appOrderDetail.getItemImg());
//                    }
//                    i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);//重新插入
                    log.info("拉取付款预售订单{}，订单金额变动appOrderDetailDatabase={}--appOrderDetail={}", appOrderDetail.getTradeId()
                            , JSON.toJSONString(appOrderDetailDatabase), JSON.toJSONString(appOrderDetail));
                    if (i > 0) {
                        log.info("拉取付款预售订单{}，订单金额变动重新插入成功", appOrderDetail.getTradeId());
                        i = 3;//代表是更新预售订单订单
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i;
    }

    /**
     * 处理预付款订单订单金额变动问题
     *
     * @param appUser
     * @param appGoods
     * @param order
     * @param userOrders
     */
    public void handlePreparePayOrder(AppUser appUser, AppGoods appGoods, AppOrderDetail order, List<AppUserOrder> userOrders, boolean isNeedSend) {

        //订单金额变动，第二次处理预售订单
        if (!CollectionUtils.isEmpty(userOrders)) {
            try {
                //拿到用户佣金比例和用户返佣信息
                OrderNewScheme orderNewScheme = handleCustomerMoney(appUser, order);
                Integer orderScale = orderNewScheme.getOrderScale();//下单用户佣金比例
                Integer parentScale = orderNewScheme.getParentScale();//上级佣金比例
                Integer twoParentScale = orderNewScheme.getTwoParentScale();//上上级佣金比例
                //获取用户杀熟佣金比例
                BigDecimal customerMoney = orderNewScheme.getCustomerMoney();

                for (AppUserOrder appUserOrder_ : userOrders) {
                    AppUserOrder appUserOrderNew = new AppUserOrder();
                    appUserOrderNew.setTableId(appUserOrder_.getTableId());

                    if (appUserOrder_.getOrderGrade() == 1) {

                        appUserOrderNew.setCommission(customerMoney.
                                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                                BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney));
                        appUserOrderNew.setSpareMoney((customerMoney.
                                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                                BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney)).add(BigDecimalUtils.Format(appGoods == null ? 0d : appGoods.getCouponmoney())));
                        int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrderNew);
                        log.info("更新用户预售订单中间表数据是否成功{},：用户id：{}:订单{}", i2, appUser.getUserId(), order.getTradeId());
                        if (i2 > 0) {
                            if (isNeedSend) {
                                try {
                                    iAppNewsLogService.newsType(appUser.getUserId(),
                                            NewsEnumLog.NEWS_ORDER_PAY.getNewsType(),
                                            appUserOrderNew.getCommission(), appGoods == null ? "" : appGoods.getItemshorttitle(), (appUserOrderNew.getCommission().add(new BigDecimal(appGoods == null ? "0" : appGoods.getCouponmoney() + ""))).toString());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log.info("更新用户预售付款订单{}入关联库成功发消息异常", order.getTradeId());
                                } finally {
                                    log.info("更新用户预售付款订单{}入关联库成功", order.getTradeId());
                                }
                            }
                        } else {
                            log.error("更新用户预售付款订单{}入关联库失败", order.getTradeId());
                        }
                    } else if (appUserOrder_.getOrderGrade() == 2) {
                        appUserOrderNew.setCommission(BigDecimalUtils.FanliMoney(String.valueOf(parentScale),
                                BigDecimalUtils.Format(customerMoney)).
                                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                                BigDecimal.valueOf(0.01) : BigDecimalUtils.FanliMoney(String.valueOf(parentScale),
                                BigDecimalUtils.Format(customerMoney)));
                        appUserOrderNew.setSpareMoney((customerMoney.
                                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                                BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney)).add(BigDecimalUtils.Format(appGoods == null ? 0d : appGoods.getCouponmoney())));

                        int i3 = iAppUserOrderService.updateAppUserOrder(appUserOrderNew);
                        if (i3 > 0) {
                            if (isNeedSend) {
                                try {
                                    iAppNewsLogService.newsType(appUserOrderNew.getUserId(),
                                            NewsEnumLog.NEWS_ORDER_SUPER_PAY.getNewsType(),
                                            appUserOrderNew.getCommission(), appUserOrderNew.getCommission().toString());
                                    // TODO: 粉丝下单成功公众号提醒
                                    //ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser,"30004",order.getItemTitle(),"省鸭APP",order.getAlipayTotalPrice().toString(),null);
                                    //log.info("粉丝下单成功公众号提醒返回结果{}", JSONObject.toJSONString(result));
                                    //this.weCheatMessage(appUser, "3004", appUserOrderNew.getCommission().toString());
                                    //log.info("更新用户预售付款订单{}一级分佣成功{}", i3, order.getTkStatus());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log.info("更新用户预售付款订单{}一级分佣成功", order.getTradeId());
                                } finally {
                                    log.info("更新用户预售付款订单{}一级分佣成功", order.getTradeId());
                                }
                            }

                        } else {
                            log.error("更新用户预售付款订单{}一级分佣失败", i3);
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public Object testHandle(Long userId, Long tradeId) {
        AppUser appUser = appUserService.selectAppUserByUserId(userId);
        AppOrderDetail appOrderDetail = appOrderDetailService.selectAppOrderDetailByTradeId(tradeId);
        OrderNewScheme orderNewScheme = handleCustomerMoney(appUser, appOrderDetail);
        return orderNewScheme;
    }
    //处理分佣
    public OrderNewScheme handleCustomerMoney(AppUser appUser, AppOrderDetail appOrderDetail){
        Object schme = null;
        String pubSharePreFee = appOrderDetail.getPubSharePreFee();

        //查询商品是否走特殊分佣渠道(渠道，商品)
        SyChannelGoods syChannelGoods = syChannelGoodsService.selectByCompanyIdAndItemId(appUser,appOrderDetail.getItemId());
        if(syChannelGoods != null){
            log.info("========订单号为：{}，走特殊商品分佣渠道",appOrderDetail.getTradeId());
            //特殊分佣处理
            schme = syChannelGoodsService.getShemeNew(syChannelGoods);
        }else {
			log.info("========订单号为：{}，走普通分佣渠道",appOrderDetail.getTradeId());
            //拿到用户佣金比例(普通)
            schme = userCashschemeService.getShemeNew(appUser.getUserId(), BigDecimalUtils.Format(pubSharePreFee).doubleValue());
        }

        Integer orderScale = null;
        Integer parentScale = null;
        Integer twoParentScale = null;
        //获取用户杀熟佣金比例
        if (schme instanceof AppOrderFeeScheme) {
            AppOrderFeeScheme orderFeeScheme = (AppOrderFeeScheme) schme;
            int countOrderNum = iAppUserOrderService.countBingOrderSum(appUser.getUserId());
            if (orderFeeScheme.getOneorder() > countOrderNum) {
                orderScale = orderFeeScheme.getOneorderScale();
            } else if (orderFeeScheme.getTwoorder() > countOrderNum) {
                orderScale = orderFeeScheme.getTwoorderScale();
            } else if (orderFeeScheme.getThirdorder() > countOrderNum) {
                orderScale = orderFeeScheme.getThirdorderScale();
            }
            parentScale = orderFeeScheme.getOneAgentScale();
            twoParentScale = orderFeeScheme.getTwoAgentScale();
        }
        //获取用户分佣佣金比例
        if (orderScale == null) {
            AppGeneralFeeScheme generalFeeScheme = (AppGeneralFeeScheme) schme;
            double commission = BigDecimalUtils.Format(pubSharePreFee).doubleValue();
            if (generalFeeScheme.getOnepay() >= commission) {
                orderScale = generalFeeScheme.getOnepayScale();
            } else if (generalFeeScheme.getTwopay() >= commission) {
                orderScale = generalFeeScheme.getTwopayScale();
            } else if (generalFeeScheme.getThirdpay() >= commission) {
                orderScale = generalFeeScheme.getThirdpayScale();
            } else if (generalFeeScheme.getForpay() >= commission) {
                orderScale = generalFeeScheme.getForpayScale();
            } else if (generalFeeScheme.getFivepay() >= commission) {
                orderScale = generalFeeScheme.getFivepayScale();
            }else if (generalFeeScheme.getSixpay() >= commission) {
                orderScale = generalFeeScheme.getSixpayScale();
            }else if (generalFeeScheme.getSevenpay() >= commission) {
                orderScale = generalFeeScheme.getSevenpayScale();
            }
            parentScale = generalFeeScheme.getOneAgentScale();
            twoParentScale = generalFeeScheme.getTwoAgentScale();
        }
        BigDecimal customerMoney = BigDecimalUtils.FanliMoney(String.valueOf(orderScale), BigDecimalUtils.Format(pubSharePreFee == null ? "0" : pubSharePreFee));

        OrderNewScheme orderNewScheme = new OrderNewScheme();
        orderNewScheme.setCustomerMoney(customerMoney);
        orderNewScheme.setParentScale(parentScale);
        orderNewScheme.setTwoParentScale(twoParentScale);
        orderNewScheme.setOrderScale(orderScale);

        return orderNewScheme;
    }

    /**
     * 获取失效订单
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus       13
     * @param orderCountType
     * @param orderQueryType
     * @param orderScene
     * @return
     */
    @Async
    public void getFailOrderDetail(String session, String startTime, String endTime, long pageNo,
                                   long tkStatus, long orderCountType, String orderQueryType, long orderScene, int type,String positionIndex ) {

        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 8;

        try {
            // TODO Auto-generated method getFailOrderDetail获取渠道的失效订单
            String str = OrderMainNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene,positionIndex);
            if (redisLockService.lock("getFailOrderDetail" + "doOrderDetailFromTBK", (System.currentTimeMillis() + 1000L * 60L * 19L) + "")) {
                log.info("获取到失效数据：{}", str);
            } else if (type == 1 || pageNo > 1) {
                log.info("获取到失效数据：{}", str);
            }
            TbkScOrderDetailsGetResponse info = JsonUtils.getJsonToBean(str, TbkScOrderDetailsGetResponse.class);
            if (info != null && info.isSuccess() && info.getData() != null && info.getData().getResults() != null && info.getData().getResults().size() > 0) {
                //#####位点，除第一页之外，都需要传递；前端原样返回。#####
                positionIndex = info.getData().getPositionIndex();

                for (TbkScOrderDetailsGetResponse.PublisherOrderDto order : info.getData().getResults()) {

                    AppUser appUser = UserMainNew(order);//关联用户
                    if(StringUtils.isEmpty(appUser)) {
                        log.info("失效订单关联不到用户,order={}itemId={}relationID={}", order.getTradeId(),order.getItemId(),order.getRelationId());
                        continue;
                    }
                    AppOrderDetail appOrderDetail = OrderDteailMainNew(order, appUser);
                    //获取锁
                    if (!redisLockService.lock(order.getTradeId() + "doOrderDetailFromTBK", startTimes + "")) {
                        continue;
                    }

                    int i = 0;
                    AppOrderDetail appOrderDetailDatabase = iAppOrderDetailService.selectAppOrderDetailByTradeId(Long.parseLong(order.getTradeId()));
                    if (appOrderDetailDatabase != null && appOrderDetailDatabase.getTradeId() != null) {
                        appOrderDetail.setPubSharePreFee("0");
                        //appOrderDetail.setFanliMoney(BigDecimal.valueOf(0));
                        appOrderDetail.setGoodFrees(appOrderDetailDatabase.getGoodFrees());
                        appOrderDetail.setItemPic(appOrderDetailDatabase.getItemPic());
                        appOrderDetail.setFanliMoney(appOrderDetailDatabase.getFanliMoney());
                        i = 2;
                    }

                    //查询商品
                    AppGoods appGoods = getAppgoods(order.getItemId().toString(), appOrderDetail);

                    if (appOrderDetailDatabase == null ||
                            (appOrderDetailDatabase != null && appOrderDetailDatabase.getTradeId() != null && appOrderDetailDatabase.getTkStatus() != null && appOrderDetailDatabase.getTkStatus() != 13)) {

                        appOrderDetail.setItemPic(appGoods == null ? "" : appGoods.getItempic());
                        //redis获取订单来源
                        String s = addBuySource(appUser.getUserId(), order.getItemId());
                        appOrderDetail.setBuySource(s);
                        i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
                        log.info("失效订单{}入库成功", order.getTradeId());
                    }else {
                        appOrderDetail.setBinding(appOrderDetailDatabase.getBinding());
                        appOrderDetail.setBindingTime(appOrderDetailDatabase.getBindingTime());
                        appOrderDetail.setDeleted(appOrderDetailDatabase.getDeleted());
                        if (appOrderDetailDatabase.getItemPic() == null || "".equals(appOrderDetailDatabase.getItemPic())
                                || appOrderDetailDatabase.getItemImg() == null || "".equals(appOrderDetailDatabase.getItemImg())
                                ) {
                            if (appOrderDetail.getItemPic() == null) {
                                appOrderDetail.setItemPic("http:" + appOrderDetail.getItemImg());
                            }
                            //redis获取订单来源
                            String s = addBuySource(appUser.getUserId(), order.getItemId());
                            appOrderDetail.setBuySource(s);
                            i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
                            if (i > 0) {
                                i = 2;
                            }
                        }
                    }

                    if (i > 0) {

                        List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));

                        //如果是维权订单就不处理了。
                        if (userOrders != null && userOrders.size() > 0 && userOrders.get(0) != null && userOrders.get(0).getOrderSettleStatus() != null && userOrders.get(0).getOrderSettleStatus() == 3) {
                            continue;
                        }
                        //如果是已失效订单就不处理了。
                        if (userOrders != null && userOrders.size() > 0 && userOrders.get(0) != null && userOrders.get(0).getOrderStatus() != null && userOrders.get(0).getOrderStatus() == 13) {
                            continue;
                        }
                        if (userOrders == null || userOrders.size() <= 0) {

                            //非免单商品//走正常分佣
                            boolean isGoSchema = goSchema(appUser, appOrderDetail, appGoods);
                            userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));
                        }

                        AppUserOrder appUserOrder = new AppUserOrder();
                        for (AppUserOrder userOrder : userOrders) {
                            if (userOrder != null && userOrder.getOrderId() != null && userOrder.getOrderStatus() == 13) {
                                log.info("message失效订单{}处理过了用户为{}", userOrder.getOrderId(), userOrder.getUserId());
                            } else {
                                //判断如果订单是无效订单，同时已经结算过3，需要从该用户的账户中扣除返佣
                                if(userOrder.getOrderStatus() == 3){
                                    //扣除用户无效订单返佣
                                    handleUserBalance(userOrder.getUserId(),userOrder.getCommission());
                                }
                                appUserOrder.setTableId(userOrder.getTableId());
                                appUserOrder.setOrderStatus(13);
                                appUserOrder.setCommission(BigDecimal.valueOf(0));
                                int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrder);
                                if (i2 > 0) {
                                    //查询失效订单是否有红包有红包就把红包设置成失效4
                                    int appRedMoney = IAppUserRedRewardService.updateAppUserRedReward(userOrder.getOrderId(), 4);
                                    AppUserRedReward appUserRedReward = IAppUserRedRewardService.selectAppUserRedRewardById(userOrder.getOrderId(), userOrder.getUserId());
                                    if (appUserRedReward != null) {
                                        updateUserCommon.UpdateUserTaskStatus(appUserRedReward.getUserId(), 6);
                                    }

                                    log.info("设置订单失效是否{}成功订单id{}用户id{}", appRedMoney, userOrder.getOrderId(), userOrder.getUserId());
                                    //未付款失效订单不发消息
                                    if(!org.apache.commons.lang3.StringUtils.isEmpty(order.getAlipayTotalPrice()) &&
                                    new BigDecimal(order.getAlipayTotalPrice()).compareTo(BigDecimal.ZERO) > 0){
                                        switch (userOrder.getOrderGrade()) {
                                            case 1:
                                                iAppNewsLogService.newsType(userOrder.getUserId(),
                                                        NewsEnumLog.NEWS_ORDER_FAIL.getNewsType(),
                                                        BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
                                                break;
                                            case 2:
                                                iAppNewsLogService.newsType(userOrder.getUserId(),
                                                        NewsEnumLog.NEWS_ORDER_SUPER_FAIL.getNewsType(),
                                                        BigDecimalUtils.Format(userOrder.getCommission()), userOrder.getCommission().toString());
                                                break;
                        /*	case 3:
                                iAppNewsLogService.newsType(userOrder.getUserId(),
                                        NewsEnumLog.NEWS_ORDER_LEVEL_FAIL.getNewsType(),
                                        BigDecimalUtils.Format(userOrder.getCommission()),userOrder.getCommission().toString());
                                break;*/
                                            default:
                                                break;
                                        }
                                    }

                                    log.info("messagemessage失效订单处理成功{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                                } else {
                                    log.info("messagemessage失效订单处理失败{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                                }
                            }
                        }
                    } else {
                        log.error("失效订单{}入库失败{}", order.getTradeId(), new Throwable().getStackTrace());
                    }
                }//for循环结束

                if (info.getData().getHasNext()) {
                    getFailOrderDetail(
                            session, startTime, endTime, pageNo + 1, tkStatus,
                            orderCountType, orderQueryType, orderScene, type,positionIndex);
                }

//                return ServerResponse.createBySuccess("数据获取成功", info.getData().getResults());
            } else {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (type == 0) {
                this.countLauncherFail.countDown();
            }
        }
        return;

    }

    /**
     * 扣除用户无效订单返佣
     * @param userId
     * @param commission
     */
    private void handleUserBalance(Long userId, BigDecimal commission) {
        log.info("扣除无效用户返佣，用户id：{},扣除金额：{}",userId,commission);

        AppUser appUser = appUserService.selectAppUserByUserId(userId);
        if(appUser != null && commission !=null && appUser.getBalance() !=null){
            BigDecimal balance = appUser.getBalance();
            BigDecimal newBalance = balance.subtract(commission);
            log.info("扣除无效用户id：{},返佣后金额：{}",userId,newBalance);

            appUser.setBalance(newBalance);
            appUserService.updateById(appUser);

        }

    }

    /**
     * 获取成功订单
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus       14
     * @param orderCountType
     * @param orderQueryType
     * @param orderScene
     * @return
     */
    @Async
    public void getSuccOrderDetail(String session, String startTime, String endTime, long pageNo,
                                   long tkStatus, long orderCountType, String orderQueryType, long orderScene, int type,String positionIndex) {

        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 8;

        try {
            // TODO Auto-generated method getFailOrderDetail获取渠道的失效订单
            String str = OrderMainNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene,positionIndex);
            if (redisLockService.lock("getSuccOrderDetail" + "doOrderDetailFromTBK", (System.currentTimeMillis() + 1000L * 60L * 19L) + "")) {
                log.info("获取到成功数据：{}", str);
            } else if (type == 1 || pageNo > 1) {
                log.info("获取到成功数据：{}", str);
            }            TbkScOrderDetailsGetResponse info = JsonUtils.getJsonToBean(str, TbkScOrderDetailsGetResponse.class);
            if (info.isSuccess() && info != null && info.getData() != null && info.getData().getResults() != null && info.getData().getResults().size() > 0) {
                //#####位点，除第一页之外，都需要传递；前端原样返回。#####
                positionIndex = info.getData().getPositionIndex();

                AppUserOrder appUserOrder = new AppUserOrder();
                for (TbkScOrderDetailsGetResponse.PublisherOrderDto order : info.getData().getResults()) {
                    AppUser appUser = UserMainNew(order);
                    if(StringUtils.isEmpty(appUser)) {
                        log.info("成功订单关联不到用户,order={}itemId={}relationID={}", order.getTradeId(),order.getItemId(),order.getRelationId());
                        continue;
                    }
                    AppOrderDetail appOrderDetail = OrderDteailMainNew(order, appUser);

                    //获取锁
                    if (!redisLockService.lock(order.getTradeId() + "doOrderDetailFromTBK", startTimes + "")) {
                        continue;
                    }

                    int i = 0;

                    //免单处理
                    AppOrderDetail appOrderDetailDatabase = iAppOrderDetailService.selectAppOrderDetailByTradeId(Long.parseLong(order.getTradeId()));


                    if (appOrderDetailDatabase != null && appOrderDetailDatabase.getTradeId() != null) {
                        appOrderDetail.setGoodFrees(appOrderDetailDatabase.getGoodFrees());
                        appOrderDetail.setItemPic(appOrderDetailDatabase.getItemPic());
                        appOrderDetail.setFanliMoney(appOrderDetailDatabase.getFanliMoney());
                        i = 2;
                    }
                    //查询商品
                    AppGoods appGoods = getAppgoods(order.getItemId().toString(), appOrderDetail);

                    //订单数据库已经存在
                    if (appOrderDetailDatabase == null ||
                            (appOrderDetailDatabase != null && appOrderDetailDatabase.getTradeId() != null && appOrderDetailDatabase.getTkStatus() != null && appOrderDetailDatabase.getTkStatus() != 13)) {
                        appOrderDetail.setBinding(appOrderDetailDatabase.getBinding());
                        appOrderDetail.setBindingTime(appOrderDetailDatabase.getBindingTime());
                        appOrderDetail.setDeleted(appOrderDetailDatabase.getDeleted());
                        appOrderDetail.setItemPic(appGoods.getItempic());
                        //redis获取订单来源
                        String s = addBuySource(appUser.getUserId(), appOrderDetail.getItemId());
                        appOrderDetail.setBuySource(s);
                        i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
                        log.info("成功订单{}入库成功", order.getTradeId());

                    } else {
                        if (appOrderDetailDatabase.getItemPic() == null || "".equals(appOrderDetailDatabase.getItemPic())
                                || appOrderDetailDatabase.getItemImg() == null || "".equals(appOrderDetailDatabase.getItemImg())
                                ) {
                            if (appOrderDetail.getItemPic() == null) {
                                appOrderDetail.setItemPic("http:" + appOrderDetail.getItemImg());
                            }
                            //redis获取订单来源
                            String s = addBuySource(appUser.getUserId(), appOrderDetail.getItemId());
                            appOrderDetail.setBuySource(s);
                            i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
                            if (i > 0) {
                                i = 2;
                            }
                        }
                        //判断是预售订单
                        i = judgePreparePayOrder(appOrderDetail, appOrderDetailDatabase);
                    }

                    if (i > 0) {

                        List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));
                        //订单金额变动，第二次处理预售订单
                        if (i == 3 && !CollectionUtils.isEmpty(userOrders)) {
                            handlePreparePayOrder(appUser, appGoods, appOrderDetail, userOrders, false);
                            userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));
                        }

                        //如果是维权订单就不处理了。
                        if (userOrders != null && userOrders.size() > 0 && userOrders.get(0) != null && userOrders.get(0).getOrderSettleStatus() != null && userOrders.get(0).getOrderSettleStatus() == 3) {
                            continue;
                        }
                        //如果是完成订单就不处理了。
                        if (userOrders != null && userOrders.size() > 0 && userOrders.get(0) != null && userOrders.get(0).getOrderSettleStatus() != null && userOrders.get(0).getOrderSettleStatus() == 14) {
                            continue;
                        }
                        if (userOrders == null || userOrders.size() <= 0) {

                            //非免单商品//走正常分佣
                            boolean isGoSchema = goSchema(appUser, appOrderDetail, appGoods);
                            userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));
                        }

                        for (AppUserOrder userOrder : userOrders) {
                            if (userOrder != null && userOrder.getOrderId() != null && userOrder.getOrderStatus() == 14) {
                                log.info("message成功订单{}处理过了用户为{}", userOrder.getOrderId(), userOrder.getUserId());
                            } else {
                                appUserOrder.setTableId(userOrder.getTableId());
                                appUserOrder.setOrderStatus(14);
                                int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrder);
                                if (i2 > 0) {
                                    switch (userOrder.getOrderGrade()) {
                                        case 1:
//									iAppNewsLogService.newsType(userOrder.getUserId(),
//											NewsEnumLog.NEWS_ORDER_SUCC.getNewsType(),
//											BigDecimalUtils.Format(userOrder.getCommission()));
                                            break;
                                        case 2:
//									iAppNewsLogService.newsType(userOrder.getUserId(),
//											NewsEnumLog.NEWS_ORDER_SUPER_SUCC.getNewsType(),
//											BigDecimalUtils.Format(userOrder.getCommission()));
                                            break;
                                        case 3:
//									iAppNewsLogService.newsType(userOrder.getUserId(),
//											NewsEnumLog.NEWS_ORDER_LEVEL_SUCC.getNewsType(),
//											BigDecimalUtils.Format(userOrder.getCommission()));
                                            break;
                                        default:
                                            break;
                                    }
                                    log.info("messagemessage成功订单处理成功{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                                } else {
                                    log.info("messagemessage成功订单处理失败{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                                }
                            }
                        }
                    } else {
                        log.error("成功订单{}入库失败{}", order.getTradeId(), new Throwable().getStackTrace());
                    }
                }//for循环结束
                if (info.getData().getHasNext()) {
                    getSuccOrderDetail(
                            session, startTime, endTime, pageNo + 1, tkStatus,
                            orderCountType, orderQueryType, orderScene, type,positionIndex);
                }

//                return ServerResponse.createBySuccess("数据获取成功", info.getResults());
            } else {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (type == 0) {
                this.countLauncherDone.countDown();
            }
        }
        return;

    }

    /**
     * 获取结算订单
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus       3
     * @param orderCountType
     * @param orderQueryType
     * @param orderScene
     * @return
     */
    @Async("myTaskAsyncPool2")
    public void getSettleOrderDetail(String session, String startTime, String endTime, long pageNo,long tkStatus, long orderCountType,
                                     String orderQueryType, long orderScene,int type,String positionIndex) {

        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 8;

        try {
            // TODO Auto-generated method getFailOrderDetail获取渠道的失效订单
            String str = OrderMainNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene,positionIndex);
            if (redisLockService.lock("getSettleOrderDetail" + "doOrderDetailFromTBK", (System.currentTimeMillis() + 1000L * 60L * 19L) + "")) {
                log.info("获取到结算数据：{}", str);
            } else if (type == 1 || pageNo > 1) {
                log.info("获取到结算数据：{}", str);
            }
            TbkScOrderDetailsGetResponse info = JsonUtils.getJsonToBean(str, TbkScOrderDetailsGetResponse.class);
            if (info.isSuccess() && info != null && info.getData()!=null && info.getData().getResults() != null && info.getData().getResults().size() > 0) {
                //#####位点，除第一页之外，都需要传递；前端原样返回。#####
                positionIndex = info.getData().getPositionIndex();

                for (TbkScOrderDetailsGetResponse.PublisherOrderDto order : info.getData().getResults()) {

                    AppUserOrder appUserOrder = new AppUserOrder();
                    AppUserOrder userOrder2 = new AppUserOrder();//构建佣金延迟

                    AppUser appUser = UserMainNew(order);
                    if(StringUtils.isEmpty(appUser)) {
                        log.info("结算订单关联不到用户,order={}itemId={}relationID={}", order.getTradeId(),order.getItemId(),order.getRelationId());
                        continue;
                    }
                    AppOrderDetail appOrderDetail = OrderDteailMainNew(order, appUser);

                    //获取锁
                    if (!redisLockService.lock(order.getTradeId() + "doOrderDetailFromTBK", startTimes + "")) {
                        continue;
                    }

                    int i = 0;
                    AppOrderDetail appOrderDetailDatabase = iAppOrderDetailService.selectAppOrderDetailByTradeId(Long.parseLong(order.getTradeId()));

                    if (appOrderDetailDatabase != null && appOrderDetailDatabase.getTradeId() != null) {
                        appOrderDetail.setGoodFrees(appOrderDetailDatabase.getGoodFrees());
                        appOrderDetail.setItemPic(appOrderDetailDatabase.getItemPic());
                        appOrderDetail.setFanliMoney(appOrderDetailDatabase.getFanliMoney());
                        i = 1;
                    }

                    if (appOrderDetailDatabase == null ||
                            (appOrderDetailDatabase != null && appOrderDetailDatabase.getTradeId() != null && appOrderDetailDatabase.getTkStatus() != null && appOrderDetailDatabase.getTkStatus() != 3)) {
                        //查询商品
                        AppGoods appGoods = getAppgoods(order.getItemId().toString(), appOrderDetail);
                        appOrderDetail.setItemPic(appGoods.getItempic());
                        //redis获取订单来源
                        String s = addBuySource(appUser.getUserId(), order.getItemId());
                        appOrderDetail.setBuySource(s);
                        i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
                        log.info("结算订单{}入库成功", order.getTradeId());
                    }else {
                        appOrderDetail.setBinding(appOrderDetailDatabase.getBinding());
                        appOrderDetail.setBindingTime(appOrderDetailDatabase.getBindingTime());
                        appOrderDetail.setDeleted(appOrderDetailDatabase.getDeleted());
                        if (appOrderDetailDatabase.getItemPic() == null || "".equals(appOrderDetailDatabase.getItemPic())
                                || appOrderDetailDatabase.getItemImg() == null || "".equals(appOrderDetailDatabase.getItemImg())
                                ) {
                            if (appOrderDetail.getItemPic() == null) {
                                appOrderDetail.setItemPic("http:" + appOrderDetail.getItemImg());
                            }
                            //redis获取订单来源
                            String s = addBuySource(appUser.getUserId(), order.getItemId());
                            appOrderDetail.setBuySource(s);
                            i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
                            if (i > 0) {
                                i = 2;
                            }
                        }

                        //订单数据库已经存在
                        //判断是预售订单
                        i = judgePreparePayOrder(appOrderDetail, appOrderDetailDatabase);
                    }

                    if (i > 0) {
                        log.info("结算订单{}入库成功-i={}", order.getTradeId(), i);
                        List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));

                        AppGoods appGoods = getAppgoods(order.getItemId().toString(), appOrderDetail);

//                        //订单金额变动，第二次处理预售订单
//                        if (i == 3 && !CollectionUtils.isEmpty(userOrders)) {
//
//                        }


                        BigDecimal userCommission = new BigDecimal("0");
                        if(!CollectionUtils.isEmpty(userOrders)) {
                            userCommission = userOrders.get(0).getCommission();
                        }
                        //如果是维权订单就不处理了。
                        if (userOrders != null && userOrders.size() > 0 && userOrders.get(0).getOrderSettleStatus() != null && userOrders.get(0).getOrderSettleStatus() == 3) {
                            continue;
                        }
                        //如果是结算订单就不处理了。
                        if (userOrders != null && userOrders.size() > 0 && userOrders.get(0).getOrderStatus() != null && userOrders.get(0).getOrderStatus() == 3) {
                            continue;
                        }
                        //如果是失效订单就不处理了。
                        if (userOrders != null && userOrders.size() > 0 && userOrders.get(0).getOrderStatus() != null && userOrders.get(0).getOrderStatus() == 13) {
                            continue;
                        }

                        if (userOrders == null || userOrders.size() <= 0) {

                            //非免单商品//走正常分佣
                            boolean isGoSchema = goSchema(appUser, appOrderDetail, appGoods);
                            userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));
                        }
                        if (//判断是预售订单
                                com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderDetail.getTbDepositTime())
                                        && com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderDetail.getTkDepositTime())
                                        && !"--".equals(appOrderDetail.getTkDepositTime())
                                        && !"--".equals(appOrderDetail.getTbDepositTime())
                                        && com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderDetail.getDepositPrice())

                                ) {
                            handlePreparePayOrder(appUser, appGoods, appOrderDetail, userOrders, false);
                            userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));
                        }

                        for (AppUserOrder userOrder : userOrders) {
                            if (userOrder != null && userOrder.getOrderId() != null && (userOrder.getOrderStatus() == 3 || userOrder.getOrderStatus() == 13)) {
                                log.info("message结算订单处理{}过了用户为{}", userOrder.getOrderId(), userOrder.getUserId());
                            } else {
                                appUserOrder.setTableId(userOrder.getTableId());
                                appUserOrder.setOrderStatus(3);
                                int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrder);
                                if (i2 > 0) {
                                    //订单结算成功修改红包状态为2
                                    //设置任务红包和邀请赚钱红包的已收货到账时间
                                    if (userOrder.getOrderGrade() == 1) {
                                        AppUserRewardSetup appUserRewardSetup = null;
                                        if (redisTemplateService.hasKey("AppUserRewardSetup")) {
                                            appUserRewardSetup = redisTemplateService.getTByKey("AppUserRewardSetup",AppUserRewardSetup.class);
                                        } else {
                                            appUserRewardSetup = iAppUserRewardSetupService.getById(1);
                                            redisTemplateService.set("AppUserRewardSetup", appUserRewardSetup, 60*60);
                                        }
                                        //邀请赚钱红包
                                        AppUserRedReward appUserRedReward = new AppUserRedReward();
                                        long expireTime = DateFormatUtils.addDate(new Date(), appUserRewardSetup.getInvitationRedMoneyExpireTime()).getTime();
                                        appUserRedReward.setExpireTime(expireTime);
                                        appUserRedReward.setOrderId(userOrder.getOrderId());
                                        appUserRedReward.setHbType(2);
                                        appUserRedReward.setHbStatus(2);
                                        int redMoneyInvi = IAppUserRedRewardService.updateAppUserRedRewardExpireTime(appUserRedReward);

                                        //任务红包
                                        AppUserRedReward appUserRedReward2 = new AppUserRedReward();
                                        long expireTime2 = DateFormatUtils.addDate(new Date(), appUserRewardSetup.getTaskRedMoneyExpireTime()).getTime();
                                        appUserRedReward2.setExpireTime(expireTime2);
                                        appUserRedReward2.setOrderId(userOrder.getOrderId());
                                        appUserRedReward2.setHbType(3);
                                        appUserRedReward2.setHbStatus(2);
                                        int redMoneyTask = IAppUserRedRewardService.updateAppUserRedRewardExpireTime(appUserRedReward2);
                                        //增加或修改任务日志状态
                                        AppUserRedReward userRedReward = IAppUserRedRewardService.selectAppUserRedRewardById(userOrder.getOrderId(), userOrder.getUserId());
                                        if (userRedReward != null) {
                                            log.info("订单结算---更新日志状态红包userI{}", userRedReward.getUserId());
                                            updateUserCommon.UpdateUserTaskStatus(userRedReward.getUserId(), 4);
                                        }
//                                      int readMoney = IAppUserRedRewardService.updateAppUserRedReward(userOrder.getOrderId(),2);
                                        log.info("订单结算更新红包状态订单号{}用户id{}邀请赚钱红包是否成功{}任务红包是否成功{}", userOrder.getOrderId(), userOrder.getUserId(), redMoneyInvi, redMoneyTask);
                                    }
                                    //查询是否是免单库的商品
                                    //GoodsFree goods = iGoodsFreeService.selectByGoodsIdAll(order.getItemId());
                                    if (appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1) {
                                        //计算总佣金
                                        try {
                                            iGoodsFreeService.updateTotalRetureAmountByGoodsId(appOrderDetail.getItemId().intValue());
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                        AppUserOrder userOrder4 = new AppUserOrder();//构建佣金延迟
                                        userOrder4.setLargeAmountYes(1);
                                        userOrder4.setLargeAmountTime(getDateTime(10));//延迟天数毫秒
                                        userOrder4.setTableId(userOrder.getTableId());
                                        userOrder4.setOrderSettleStatus(1);
                                        userOrder4.setOrderStatus(3);
                                        int i3 = iAppUserOrderService.updateAppUserOrder(userOrder4);
                                        log.info("结算订单(免单延迟)结果", i3);
//                                            int i6 = iAppUserService.updateAppUseraddbalance(appUser.getUserId(),
//                                                    BigDecimalUtils.Format(userOrder.getCommission()));
                                        if (i3 > 0 && isSendMsg(7)) {
                                            iAppNewsLogService.newsType(appUser.getUserId(),
                                                    NewsEnumLog.NEWS_FREE_BIGDELAY.getNewsType(),
                                                    BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
                                        }

                                        try {
                                            // TODO: 结算成功公众号提醒
                                            log.info("app_order_detail的trade_id:{}",appOrderDetail.getTradeId());
                                            BigDecimal commission = userOrder.getCommission();
                                            String commissionStr = "0";
                                            if(commission != null){
                                                commissionStr = userOrder.getCommission().toString();
                                            }
                                            commissionStr +="元";
                                            String tkEarningTime = appOrderDetail.getTkEarningTime();
                                            if(tkEarningTime == null){
                                                tkEarningTime = "暂无";
                                            }
                                            ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser,"30006",appOrderDetail.getTradeId().toString(),commissionStr,tkEarningTime,appUser.getWechatNickname());
                                            log.info("公众号发消1息返回结果{}", JSONObject.toJSONString(result));
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                    } else {
                                        //查询佣金是否符合佣金冻结设置
                                        CommissionFreeze freeze = null;
                                        if (redisTemplate.hasKey("CommissionFreezeStuep")) {
                                            freeze = (CommissionFreeze) redisTemplate.opsForValue().get("CommissionFreezeStuep");
                                        } else {
                                            freeze = iCommissionFreezeService.selectByPrimaryKeyLIMIT(1);
                                            redisTemplate.opsForValue().set("CommissionFreezeStuep", freeze, 1, TimeUnit.HOURS);
                                        }
                                        //相等返回0，大于返回1，小于返回-1
                                        if (BigDecimalUtils.Format(userCommission).compareTo(
                                                BigDecimalUtils.Format(freeze.getCommissionlimit())) > 0) {
                                            userOrder2.setLargeAmountYes(1);
                                            userOrder2.setLargeAmountTime(getDateTime(freeze.getDelaydays()));//延迟天数毫秒
                                            userOrder2.setTableId(userOrder.getTableId());
                                            userOrder2.setOrderSettleStatus(1);
                                            userOrder2.setOrderStatus(3);
                                            int i3 = iAppUserOrderService.updateAppUserOrder(userOrder2);
                                            log.info("结算订单(普通商品延迟){}", i3);
                                            if (i3 > 0 && isSendMsg(7)) {
                                                iAppNewsLogService.newsType(appUser.getUserId(),
                                                        NewsEnumLog.NEWS_BIGDELAY.getNewsType(),
                                                        BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
                                            }
                                        } else {
                                           BigDecimal beforeBalance=appUser.getBalance();
                                            //根据订单id查询订单
                                            switch (userOrder.getOrderGrade()) {
                                                case 1:
                                                    int i3 = iAppUserService.updateAppUseraddbalance(userOrder.getUserId(),
                                                            BigDecimalUtils.Format(userOrder.getCommission()));
                                                    log.info("message{}自己{}", userOrder.getUserId(), userOrder.getCommission());
                                                    log.info("普通商品补贴到账开始发送消息{}", i3);
                                                    if (i3 > 0) {
                                                        //新增用户余额变动日志记录
                                                        syUserMoneyLogService.addSyUserMoneyLog(userOrder.getUserId(),beforeBalance,BigDecimalUtils.Format(userOrder.getCommission()),"普通商品补贴到账",2,0);
                                                        if (isSendMsg(7)) {
                                                            iAppNewsLogService.newsType(userOrder.getUserId(),
                                                                    NewsEnumLog.NEWS_ORDER_SETTLE.getNewsType(),
                                                                    BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
                                                        }
                                                  /*      if (isSendMsg(8)) {
                                                            iAppNewsLogService.newsType(userOrder.getUserId(),
                                                                    NewsEnumLog.NEWS_ORDER_SUBSIDY.getNewsType(),
                                                                    BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
                                                        }*/

                                                        try {
                                                            // TODO: 结算成功公众号提醒
                                                            log.info("app_order_detail的trade_id:{}",appOrderDetail.getTradeId());
                                                            BigDecimal commission = userOrder.getCommission();
                                                            String commissionStr = "0";
                                                            if(commission != null){
                                                                commissionStr = userOrder.getCommission().toString();
                                                            }
                                                            commissionStr +="元";
                                                            String tkEarningTime = appOrderDetail.getTkEarningTime();
                                                            if(tkEarningTime == null){
                                                                tkEarningTime = "暂无";
                                                            }
                                                            ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser,"30006",appOrderDetail.getTradeId().toString(),commissionStr,tkEarningTime,appUser.getWechatNickname());
                                                            log.info("公众号发消1息返回结果{}", JSONObject.toJSONString(result));
                                                        } catch (Exception e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                    break;
                                                case 2:
                                                    int i4 = iAppUserService.updateAppUseraddbalance(userOrder.getUserId(),
                                                            BigDecimalUtils.Format(userOrder.getCommission()));
                                                    log.info("message{}2级{}", userOrder.getUserId(), userOrder.getCommission());
                                                    log.info("普通商品补贴到账开始发送消息{}", i4);
                                                    if (i4 > 0) {

                                                        //新增用户余额变动日志记录
                                                        syUserMoneyLogService.addSyUserMoneyLog(userOrder.getUserId(),beforeBalance,BigDecimalUtils.Format(userOrder.getCommission()),"普通商品2级补贴到账",2,0);
                                                        if (isSendMsg(7)) {
                                                            iAppNewsLogService.newsType(userOrder.getUserId(),
                                                                    NewsEnumLog.NEWS_ORDER_SUPER_SETTLE.getNewsType(),
                                                                    BigDecimalUtils.Format(userOrder.getCommission()), userOrder.getCommission().toString());
                                                        }
                                                      /*  if (isSendMsg(8)) {
                                                            iAppNewsLogService.newsType(userOrder.getUserId(),
                                                                    NewsEnumLog.NEWS_ORDER_SUPER_SETTLE.getNewsType(),
                                                                    BigDecimalUtils.Format(userOrder.getCommission()),  userOrder.getCommission().toString());
                                                        }*/
                                                        // TODO: 好友结算成功公众号提醒
//                                                        ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser,"30003","***",appOrderDetail.getTradeId().toString(), appOrderDetail.getAlipayTotalPrice(),userOrder.getCommission().toString());
//                                                        log.info("好友结算成功公众号提醒结果{}", JSONObject.toJSONString(result));
                                                        //this.
                                                        // (appUser, "3004", BigDecimalUtils.Format(userOrder.getCommission()).toString());
                                                    }
                                                    break;
                                               /* case 3:
                                                    int i5 = iAppUserService.updateAppUseraddbalance(userOrder.getUserId(),
                                                            BigDecimalUtils.Format(userOrder.getCommission()));
                                                    log.info("message{}3级{}", userOrder.getUserId(), userOrder.getCommission());
                                                    if (i5 > 0) {
                                                        iAppNewsLogService.newsType(userOrder.getUserId(),
                                                                NewsEnumLog.NEWS_ORDER_LEVEL_SETTLE.getNewsType(),
                                                                BigDecimalUtils.Format(userOrder.getCommission()), userOrder.getCommission().toString());
                                                    }
                                                    break;*/
                                                default:
                                                    break;
//                                            }
                                            }
                                            AppUserOrder userOrder3 = new AppUserOrder();//构建佣金延迟
                                            userOrder3.setOrderStatus(3);
                                            userOrder3.setOrderSettleStatus(2);
                                            userOrder3.setTableId(userOrder.getTableId());
                                            int i4 = iAppUserOrderService.updateAppUserOrder(userOrder3);
                                            log.info("结算订单（普通商品不延迟）已经将钱转到账i4{}", i4);
                                        }
                                    }
                                    log.info("messagemessage结算订单处理成功{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                                } else {
                                    log.info("messagemessage结算订单处理失败{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                                }
                            }
                        }
                    } else {
                        log.error("结算订单{}入库失败{}", order.getTradeId(), new Throwable().getStackTrace());
                    }
                }//for循环结束
                if (info.getData().getHasNext()) {
                    getSettleOrderDetail(
                            session, startTime, endTime, pageNo + 1, tkStatus,
                            orderCountType, orderQueryType, orderScene,type,positionIndex);
                }
//                return ServerResponse.createBySuccess("数据获取成功", info.getResults());
            } else {
                return ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (type == 0) {
                this.countLauncherSuccess.countDown();
            }

        }
        return ;

    }

    @Async("myTaskAsyncPool2")
    public void getRefundOrderDetail(String session, String startTime, String endTime) {

        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 2;

        try {
            // 获取渠道的维权订单
            String str = "";
            TbkScPunishOrderGetResponse tbkScPunishOrderGetResponse = orderController.orderrefunddetailsNew(session, startTime, 1, 1, 1, null, 1);
            if (tbkScPunishOrderGetResponse != null) {
                str = JSON.toJSONString(tbkScPunishOrderGetResponse);
            }
            log.debug("获取到维权订单数据：{}", str);
            TbkOrderGetInfo info = JsonUtils.getJsonToBean(str, TbkOrderGetInfo.class);
            if (info.isSuccess() && info != null && info.getResults() != null && info.getResults().size() > 0) {
                for (NTbkOrderDataBean order : info.getResults()) {
                    //订单详情
                    AppOrderDetail appOrderDetail = OrderDteailMain(order);
                    //获取锁
                    if (!redisLockService.lock(order.getTradeId() + "getFailOrderDetail", startTimes + "")) {
                        continue;
                    }

                    int i = 0;
                    //数据库订单表中插入或者修改订单状态
                    AppOrderDetail appOrderDetail1 = iAppOrderDetailService.selectAppOrderDetailByTradeId(order.getTradeId());
                    if (appOrderDetail1 != null && appOrderDetail1.getTradeId() != null) {
                        appOrderDetail.setPubSharePreFee("0");
                        appOrderDetail.setFanliMoney(BigDecimal.valueOf(0));
                        appOrderDetail.setGoodFrees(appOrderDetail1.getGoodFrees());
                        appOrderDetail.setItemPic(appOrderDetail1.getItemPic());
                        appOrderDetail.setFanliMoney(appOrderDetail1.getFanliMoney());
                        i = 1;
                    }


                    if (appOrderDetail1 == null ||
                            (appOrderDetail1 != null && appOrderDetail1.getTradeId() != null && appOrderDetail1.getTkStatus() != null && appOrderDetail1.getTkStatus() != 4)) {
                        i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
                        log.info("维权订单{}入库成功", order.getTradeId());
                        if (i > 0) {
                            if (appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1) {
                                //查询是否是免单库的商品如果是就失效订单数加1
                                GoodsFree goods = iGoodsFreeService.selectByGoodsId(order.getNumIid());
                                if (goods != null) {
                                    log.info("获取到免单商品{}", goods.getGoodsId());
                                    iGoodsFreeService.updateInvalidOrdersByGoodsId(goods.getId());
                                }
                            }
                        }
                    }

                    if (i > 0) {
                        //查询订单，判断订单是否已经处理过是否是维权订单
                        List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(order.getTradeId());
                        AppUserOrder appUserOrder = new AppUserOrder();
                        for (AppUserOrder userOrder : userOrders) {
                            if (userOrder != null && userOrder.getOrderId() != null && userOrder.getOrderStatus() == 13) {
                                log.info("message失效订单{}处理过了用户为{}", userOrder.getOrderId(), userOrder.getUserId());
                            } else {
                                appUserOrder.setTableId(userOrder.getTableId());
                                appUserOrder.setOrderStatus(4);//维权订单
                                appUserOrder.setCommission(BigDecimal.valueOf(0));
                                int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrder);
                                if (i2 > 0) {
                                    //查询失效订单是否有红包有红包就把红包设置成失效4
                                    int appRedMoney = IAppUserRedRewardService.updateAppUserRedReward(userOrder.getOrderId(), 4);
                                    AppUserRedReward appUserRedReward = IAppUserRedRewardService.selectAppUserRedRewardById(userOrder.getOrderId(), userOrder.getUserId());
                                    if (appUserRedReward != null) {
                                        updateUserCommon.UpdateUserTaskStatus(appUserRedReward.getUserId(), 6);
                                    }

                                    log.info("设置订单维权是否{}成功订单id{}用户id{}", appRedMoney, userOrder.getOrderId(), userOrder.getUserId());
                                    switch (userOrder.getOrderGrade()) {
                                        case 1:
                                            iAppNewsLogService.newsType(userOrder.getUserId(),
                                                    NewsEnumLog.NEWS_ORDER_RIGHTS.getNewsType(),
                                                    BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
                                            break;
                                        case 2:
                                            iAppNewsLogService.newsType(userOrder.getUserId(),
                                                    NewsEnumLog.NEWS_ORDER_SUPER_RIGHTS.getNewsType(),
                                                    BigDecimalUtils.Format(userOrder.getCommission()), userOrder.getCommission().toString());
                                            break;

                                        default:
                                            break;
                                    }
                                    log.info("messagemessage维权订单处理成功{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                                } else {
                                    log.info("messagemessage维权订单处理失败{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                                }
                            }
                        }
                    } else {
                        log.error("维权订单{}入库失败{}", order.getTradeId(), new Throwable().getStackTrace());
                    }
                }//for循环结束
//                return ServerResponse.createBySuccess("数据获取成功", info.getResults());
            } else {
                return ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.countLauncherRefund.countDown();
        }
        return ;
    }

    /**
     * 统一请求方法
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus
     * @param orderCountType
     * @param orderQueryType
     * @param orderScene
     * @return
     */
    private String OrderMain(String session, String startTime, long pageNo,
                             long tkStatus, long orderCountType, String orderQueryType, long orderScene) {
        StringBuilder builder = new StringBuilder();
        builder.append("session=").append(session);
        builder.append("&startTime=").append(startTime.replace(" ", "%20"));
        builder.append("&pageNo=").append(pageNo);
        builder.append("&tkStatus=").append(tkStatus);
        builder.append("&orderCountType=").append(orderCountType);
        builder.append("&orderQueryType=").append(orderQueryType);
        builder.append("&orderScene=").append(orderScene);

//        String str = ApiUtils.postEcoData(ApiEnum.TAOBAO_ORDER_ORDERDETAILS, builder.toString());
        String str = "";
//        TbkScOrderGetResponse tbkScOrderGetResponse = orderController.orderDetails(session, startTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene);
//        if (tbkScOrderGetResponse != null) {
//            str = JSON.toJSONString(tbkScOrderGetResponse);
//        }
        return str;
    }

    /**
     * 统一请求方法
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus
     * @param orderScene
     * @return
     */
    private String OrderMainNew(String session, String startTime, String endTime, long pageNo,
                             long tkStatus, long orderCountType, String orderQueryType, long orderScene,String positionIndex) {
        String str = "";
        TbkScOrderDetailsGetResponse tbkScOrderDetailsGetResponse = orderController.orderDetailsNew(session, startTime, endTime, pageNo, tkStatus,orderCountType, orderQueryType, orderScene,positionIndex);
        if (tbkScOrderDetailsGetResponse != null) {
            str = JSON.toJSONString(tbkScOrderDetailsGetResponse);
        }
        return str;
    }

    /**
     * 获取用户信息
     *
     * @param order
     * @return
     */
    private AppUser UserMain(NTbkOrderDataBean order) {
        AppUser appUser = null;
        if (order.getRelationId() != null && order.getRelationId() != 0) {
            appUser = iAppUserService.selectUserInfoByRelationId(order.getRelationId());
        } else if (order.getSpecialId() != null) {
            appUser = iAppUserService.selectUserInfoBySpecialId(order.getSpecialId());
        }
        if (appUser == null || appUser.getUserId() == null) {
            appUser = iAppUserService.selectUserInfoBySpecialId(order.getSpecialId());
        }
        return appUser;
    }

    /**
     * 获取用户信息
     *
     * @param order
     * @return
     */
    private AppUser UserMainNew(TbkScOrderDetailsGetResponse.PublisherOrderDto order) {


        AppUser appUser = null;
        //先根据订单id去数据库中查询app_user_order表，存在再根据app_user_order表的user_id查询用户
        try {
            QueryWrapper<AppUserOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", order.getTradeId() + "");
            queryWrapper.eq("order_grade", 1);
            AppUserOrder appUserOrder = iAppUserOrderService.getOne(queryWrapper);
            if (appUserOrder != null && appUserOrder.getUserId() != null) {
                appUser = iAppUserService.selectAppUserByUserId(appUserOrder.getUserId());
            }
            if (appUser != null && appUser.getUserId() != null && appUser.getUserId() != 0) {
                return appUser;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //根据relation_id查询用户
        if (order.getRelationId() != null && order.getRelationId() != 0) {
            appUser = iAppUserService.selectUserInfoByRelationId(order.getRelationId());
        }else if (order.getSpecialId() != null && order.getSpecialId() != 0) {
            appUser = iAppUserService.selectUserInfoBySpecialId(order.getSpecialId());
        }
//        if (appUser == null || appUser.getUserId() == null || appUser.getUserId() == 0) {
//            if (order.getSpecialId() != null && order.getSpecialId() != 0) {
//                appUser = iAppUserService.selectUserInfoBySpecialId(order.getSpecialId());
//            }
//            appUser = iAppUserService.selectUserInfoBySpecialId(order.getSpecialId());
//        }
        if (appUser == null || appUser.getUserId() == null || appUser.getUserId() == 0) {
            List<AppUserOrder> appUserOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));
            if (appUserOrders != null && appUserOrders.size() > 0) {
                for (AppUserOrder appUserOrder : appUserOrders) {
                    if (appUserOrder != null && appUserOrder.getOrderGrade() != null && appUserOrder.getOrderGrade() == 1) {
                        appUser = iAppUserService.selectAppUserByUserId(appUserOrder.getUserId());
                    }
                }
            }
        }


        return appUser;
    }
    /**
     * 统一接收类
     *
     * @param order
     * @return
     */
    private AppOrderDetail OrderDteailMain(NTbkOrderDataBean order) {
        AppOrderDetail appOrderDetail = new AppOrderDetail();
        AppUser appUser = UserMain(order);
//		String key = MD5Utils.createMD5(order.getTradeId() +String.valueOf(order.getTkStatus()));
//      if(!redisTemplate.hasKey("orderId:"+key)){
//			redisTemplate.opsForValue().set("orderId:"+key ,"1",20, TimeUnit.DAYS);
        appOrderDetail.setAdzoneId(order.getAdzoneId());
        appOrderDetail.setAdzoneName(order.getAdzoneName());
        appOrderDetail.setAlipayTotalPrice(order.getAlipayTotalPrice());
        appOrderDetail.setAuctionCategory(order.getAuctionCategory());
        appOrderDetail.setClickTime(order.getClickTime() == null ? 0 : order.getClickTime().getTime());
        appOrderDetail.setCommission(order.getCommission());
        appOrderDetail.setCommissionRate(order.getCommissionRate());
        appOrderDetail.setEarningTime(order.getEarningTime() == null ? 0 : order.getEarningTime().getTime());
        appOrderDetail.setCreateTime(order.getCreateTime() == null ? 0 : order.getCreateTime().getTime());
        appOrderDetail.setItemId(order.getNumIid());
        appOrderDetail.setItemNum(order.getItemNum());
        appOrderDetail.setItemTitle(order.getItemTitle());
        appOrderDetail.setOrderDetailid(order.generateMyId(order.getTradeId().toString(), order.getNumIid().toString()));
        appOrderDetail.setOrderType(order.getOrderType());
        appOrderDetail.setPayPrice(order.getPayPrice());
        appOrderDetail.setPayStatus(order.getTkStatus().toString());
        appOrderDetail.setTkStatus(order.getTkStatus().intValue());
        appOrderDetail.setRelationId(order.getRelationId());
        appOrderDetail.setSellerNick(order.getSellerNick());
        appOrderDetail.setSellerShopTitle(order.getSellerShopTitle());
        appOrderDetail.setSiteId(order.getSiteId());
        appOrderDetail.setSiteName(order.getSiteName());
        appOrderDetail.setSpecialId(order.getSpecialId());
        appOrderDetail.setTableCreateTime(System.currentTimeMillis());
        appOrderDetail.setTableUpdateTime(System.currentTimeMillis());
        appOrderDetail.setTaobaoUserId(appUser == null ? 0 : appUser.getTaobaoUserId());
        appOrderDetail.setTotalCommissionFee(order.getTotalCommissionFee());
        appOrderDetail.setTotalCommissionRate(order.getTotalCommissionRate());
        appOrderDetail.setTradeId(order.getTradeId());
        appOrderDetail.setTradeParentId(order.getTradeParentId());
        appOrderDetail.setIncomeRate(order.getIncomeRate());
        appOrderDetail.setPubSharePreFee(order.getPubSharePreFee());
        appOrderDetail.setPrice(order.getPrice());
        appOrderDetail.setSubsidyFee(order.getSubsidyFee());
        appOrderDetail.setSubsidyRate(order.getSubsidyRate());
        appOrderDetail.setSubsidyType(order.getSubsidyType());
        appOrderDetail.setTk3rdPubId(order.getTk3rdPubId());
        appOrderDetail.setTk3rdType(order.getTk3rdType());
        appOrderDetail.setTk3rdSiteid(order.getTk3rdSiteId());
        appOrderDetail.setTk3rdAdzoneid(order.getTk3rdAdzoneId());
        appOrderDetail.setTerminalType(order.getTerminalType());
        log.info("message订单佣金{}，计算后佣金{}", order.getPubSharePreFee(), BigDecimalUtils.Format(order.getPubSharePreFee() == null ? "0" : order.getPubSharePreFee()));
        appOrderDetail.setFanliMoney(BigDecimalUtils.Format(order.getPubSharePreFee() == null ? "0" : order.getPubSharePreFee()));
        return appOrderDetail;
    }
    public String generateOrderDetailId(String childOrderId,String itemId) {
        return MD5Utils.createMD5(itemId +childOrderId);
    }
    /**
     * 统一接收类
     *
     * @param order
     * @return
     */
    private AppOrderDetail OrderDteailMainNew(TbkScOrderDetailsGetResponse.PublisherOrderDto order,AppUser appUser) {
        AppOrderDetail appOrderDetail = new AppOrderDetail();
        if (appUser == null || appUser.getUserId() == null || appUser.getUserId() == 0) {
            appUser = UserMainNew(order);
        }

//		String key = MD5Utils.createMD5(order.getTradeId() +String.valueOf(order.getTkStatus()));
//      if(!redisTemplate.hasKey("orderId:"+key)){
//			redisTemplate.opsForValue().set("orderId:"+key ,"1",20, TimeUnit.DAYS);
        appOrderDetail.setAdzoneId((order.getAdzoneId() == null ? "" : order.getAdzoneId()) + "");
        appOrderDetail.setAdzoneName(order.getAdzoneName());
        appOrderDetail.setAlipayTotalPrice(order.getAlipayTotalPrice());
        appOrderDetail.setAuctionCategory(order.getItemCategoryName());
        appOrderDetail.setClickTime(order.getClickTime() == null ? 0 : DateUtils.datestr2LongByFormt(order.getClickTime(), null));
        appOrderDetail.setCommission(order.getTotalCommissionFee());
        appOrderDetail.setCommissionRate(order.getTotalCommissionRate());
        appOrderDetail.setEarningTime(order.getTkEarningTime() == null ? 0 : DateUtils.datestr2LongByFormt(order.getTkEarningTime(), null));
        appOrderDetail.setCreateTime(order.getTkCreateTime() == null ? 0 : DateUtils.datestr2LongByFormt(order.getTkCreateTime(), null));
        appOrderDetail.setItemId(order.getItemId());
        appOrderDetail.setItemNum(order.getItemNum());
        appOrderDetail.setItemTitle(order.getItemTitle());
        appOrderDetail.setOrderDetailid(generateOrderDetailId(order.getTradeId(), order.getItemId().toString()));
        appOrderDetail.setOrderType(order.getOrderType());
        appOrderDetail.setPayPrice(order.getPayPrice());
        appOrderDetail.setPayStatus(order.getTkStatus().toString());
        appOrderDetail.setTkStatus(order.getTkStatus().intValue());
        appOrderDetail.setRelationId(order.getRelationId());
        appOrderDetail.setSellerNick(order.getSellerNick());
        appOrderDetail.setSellerShopTitle(order.getSellerShopTitle());
        appOrderDetail.setSiteId(order.getSiteId() == null ? "" : (order.getSiteId() + ""));
        appOrderDetail.setSiteName(order.getSiteName());
        appOrderDetail.setSpecialId(order.getSpecialId());
        appOrderDetail.setTableCreateTime(System.currentTimeMillis());
        appOrderDetail.setTableUpdateTime(System.currentTimeMillis());
        appOrderDetail.setTaobaoUserId(appUser == null ? 0 : appUser.getTaobaoUserId());
        appOrderDetail.setTotalCommissionFee(order.getTotalCommissionFee());
        appOrderDetail.setTotalCommissionRate(order.getTotalCommissionRate());
        appOrderDetail.setTradeId(Long.parseLong(order.getTradeId()));
        appOrderDetail.setTradeParentId(Long.parseLong(order.getTradeParentId()));
        appOrderDetail.setIncomeRate(order.getIncomeRate());
        appOrderDetail.setPubSharePreFee(order.getPubSharePreFee());
        appOrderDetail.setPrice(order.getItemPrice());
        appOrderDetail.setSubsidyFee(order.getSubsidyFee());
        appOrderDetail.setSubsidyRate(order.getSubsidyRate());
        appOrderDetail.setSubsidyType(order.getSubsidyType());
        appOrderDetail.setTk3rdPubId(order.getPubId());
//        appOrderDetail.setTk3rdType(order.getTk3rdType());
//        appOrderDetail.setTk3rdSiteid(order.getTk3rdSiteId());
//        appOrderDetail.setTk3rdAdzoneid(order.getTk3rdAdzoneId());
        appOrderDetail.setTerminalType(order.getTerminalType());

        appOrderDetail.setTkDepositTime(order.getTkDepositTime());
        appOrderDetail.setTbDepositTime(order.getTbDepositTime());
        appOrderDetail.setDepositPrice(order.getDepositPrice());
        appOrderDetail.setAppKey(order.getAppKey());
        appOrderDetail.setTkEarningTime(order.getTkEarningTime());
        appOrderDetail.setTbPaidTime(order.getTbPaidTime());
        appOrderDetail.setTkPaidTime(order.getTkPaidTime());
        appOrderDetail.setRefundTag(order.getRefundTag() == null ? 0 : order.getRefundTag());
        appOrderDetail.setItemImg(order.getItemImg());
        appOrderDetail.setTkOrderRole(order.getTkOrderRole() == null ? 0 : order.getTkOrderRole());
        appOrderDetail.setPubShareFee(order.getPubShareFee());
        appOrderDetail.setPubShareRate(order.getPubShareRate());
        appOrderDetail.setTkTotalRate(order.getTkTotalRate());
        appOrderDetail.setAlimamaRate(order.getAlimamaRate());
        appOrderDetail.setAlimamaShareFee(order.getAlimamaShareFee());
        appOrderDetail.setFlowSource(order.getFlowSource());
        appOrderDetail.setItemLink(order.getItemLink());
        appOrderDetail.setTkCommissionPreFeeForMediaPlatform(order.getTkCommissionPreFeeForMediaPlatform());
        appOrderDetail.setTkCommissionFeeForMediaPlatform(order.getTkCommissionFeeForMediaPlatform());
        appOrderDetail.setTkCommissionRateForMediaPlatform(order.getTkCommissionRateForMediaPlatform());

        log.info("message订单佣金{}，计算后佣金{}", order.getPubSharePreFee(), BigDecimalUtils.Format(order.getPubSharePreFee() == null ? "0" : order.getPubSharePreFee()));
        appOrderDetail.setFanliMoney(BigDecimalUtils.Format(order.getPubSharePreFee() == null ? "0" : order.getPubSharePreFee()));
        return appOrderDetail;
    }
    /**
     * 获取指定时间的时间戳
     * 一天是86400000
     *
     * @param start 天数
     * @return
     */
    public static long getDateTime(Integer start) {

        return org.apache.commons.lang3.time.DateUtils.addDays(new Date(), start).getTime();
    }

    public static void main(String[] args) {

//        long current = System.currentTimeMillis();    //当前时间毫秒数
//        long startTodayTime = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();  //今天零点零分零秒的毫秒数
//        long endTodayTime = startTodayTime + 24 * 60 * 60 * 1000 - 1;  //今天23点59分59秒的毫秒数
//

//        String startTime = "2019-10-28 12:14:08";
//        Date startDate = DateUtils.datestr2Date(startTime, null);
//
//        Date zeroStartTimeByDate = DateUtils.getZeroStartTimeByDate(startDate);//传入日期当天开始时间
//        Date zeroEndTimeByDate = DateUtils.getZeroEndTimeByDate(startDate);//传入日期当天结束时间
        String pubSharePreFee = "0.76";
        String orderScale = "50";

        BigDecimal customerMoney = BigDecimalUtils.FanliMoney(String.valueOf(orderScale), BigDecimalUtils.Format(pubSharePreFee == null ? "0" : pubSharePreFee));
        log.info(customerMoney.toString());
    }

    /**
     * 每日首购
     */
    private void usetTask(AppUser appUser, Long tradeId,String startTime) {
        if(startTime == null || "".equals(startTime)){
            startTime = DateFormatUtils.dateToString(new Date());
        }
        //date:2019-09-26 by:zhuchao des:根据传入日期判断红包
        Date startDate = DateUtils.datestr2Date(startTime, null);
        Date zeroStartTimeByDate = DateUtils.getZeroStartTimeByDate(startDate);//传入日期当天开始时间
        Date zeroEndTimeByDate = DateUtils.getZeroEndTimeByDate(startDate);//传入日期当天结束时间

        long startTodayTime = zeroStartTimeByDate.getTime();//传入日期当天零点零分零秒的毫秒数
        long endTodayTime = zeroEndTimeByDate.getTime();  //传入日期当天23点59分59秒的毫秒数
        log.info("开始时间{}结束时间{}", startTodayTime, endTodayTime);
        int i = iAppOrderDetailService.selectOrderIsTodayCount(startTodayTime, endTodayTime, appUser.getTaobaoUserId());
        log.info("根据订单号查询是不是当天第一次下单订单号{}用户id:{}淘宝用户id:{}==结果{}", tradeId, appUser.getUserId(), appUser.getTaobaoUserId(), i);
        if (i == 0) {
            //查询每日首购任务
            SyTaskType syTaskType = iSyTaskTypeService.selectSyTaskTypeById(6);

            //给用户加任务金币 根据用户id查询能查到修改 否则新增
            SyUserMoney oldSyUserMoney = iSyUserMoneyService.selectByUserId(appUser.getUserId());
            if (oldSyUserMoney == null) {
                SyUserMoney syUserMoney = new SyUserMoney();
                syUserMoney.setUserId(appUser.getUserId());
                syUserMoney.setGoldBalanceAmount(syTaskType.getTaskRewardNum());
                syUserMoney.setGoldTotalAmount(syTaskType.getTaskRewardNum());
                syUserMoney.setEnable(1);
                int syUserMoneyNum = iSyUserMoneyService.insertSyUserMoney(syUserMoney);
                log.info("用户增加加金币用户id{}结果{}", appUser.getUserId(), syUserMoneyNum);
            } else {
                SyUserMoney syUserMoney = new SyUserMoney();
                syUserMoney.setTableId(oldSyUserMoney.getTableId());
                syUserMoney.setUserId(appUser.getUserId());
                syUserMoney.setGoldBalanceAmount(syTaskType.getTaskRewardNum() + oldSyUserMoney.getGoldBalanceAmount());
                syUserMoney.setGoldTotalAmount(syTaskType.getTaskRewardNum() + oldSyUserMoney.getGoldTotalAmount());
                int syUserMoneyNum = iSyUserMoneyService.updateSyUserMoney(syUserMoney);
                log.info("用户修改金币用户id{}结果{}", appUser.getUserId(), syUserMoneyNum);
            }
            //增加日志
            SyUserTask syUserTask = new SyUserTask();
            syUserTask.setUserId(appUser.getUserId());
            syUserTask.setTaskTypeId(syTaskType.getTableId());
            syUserTask.setTaskType(syTaskType.getTaskType());
            syUserTask.setTaskRewardType(syTaskType.getTaskRewardType());
            syUserTask.setTaskStatus(5);
            syUserTask.setTaskRewardNum(syTaskType.getTaskRewardNum());
            syUserTask.setTaskRewardDate(new Date());
            syUserTask.setEnable(1);
            int syUserTaskNum = iSyUserTaskService.insertsyUserTask(syUserTask);
            log.info("用户加金币日志用户id{}结果{}", appUser.getUserId(), syUserTaskNum);
           /* iAppNewsLogService.newsType(appUser.getUserId(),
                    NewsEnumLog.NEWS_FIRST_PURCHASE.getNewsType(),
                    BigDecimalUtils.Format(syTaskType.getTaskRewardNum()), syTaskType.getTaskRewardNum().toString());*/
        }
    }

    /**
     * @param appUser     用户
     * @param messageType 信息类型
     *                    30001：到账提醒模板、
     *                    30002：下单成功提醒模板，
     *                    30003：收货成功模板，
     *                    30004：好友下单成功提醒
     *                    30005：邀请好友成功
     * @param amount      金额
     */
    private void weCheatMessage(AppUser appUser, String messageType, String amount) {
        try {
            log.info("公众号发消息类型{}金额{},用户{}", messageType, amount, JSONObject.toJSONString(appUser));
            ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser, messageType, appUser.getWechatNickname(), DateFormatUtils.getCurrentDate(), amount, "微信");
            log.info("公众号发消息返回结果{}", JSONObject.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
            log.info("公众号发消息异常", e.getMessage());
        }
    }


    /**
     * 通过开关判断是否要发消息
     * @id 开关类型
     * @return
     */
    private Boolean isSendMsg(int id) {
        //查询开关表是否发消息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("table_id", id);
        SySwitch sySwitch = iSySwitchService.getOne(queryWrapper);
        if (sySwitch == null) return false;
        if (sySwitch.getState() == 1) {
            log.info("消息类型{} 消息开发送消息",id);
            return true;
        }
        log.info("消息类型{} 消息关",id);
        return false;
    }


    public String addBuySource(Long userId,Long itemId){
        //redis获取buy_source
        List <Map<Object,Object>> map = (List <Map<Object,Object>>)redisTemplate.opsForList().range("app_buy_source_" + userId, 0, -1);
        if(map.size() > 0){
            List<String> orderSourceList = new ArrayList<>();
            for(Map orderSource:map){
                if(orderSource.get("itemId").equals(itemId)){
                    orderSourceList.add(orderSource.get("jumpType").toString());
                }
            }
            String orderSourceStr = Joiner.on(",").join(orderSourceList);
            return orderSourceStr;
        }
        return null;
    }


    private CountLauncherPay countLauncherPay;

    private CountLauncherFail countLauncherFail;

    private CountLauncherSuccess countLauncherSuccess;

    private CountLauncherDone countLauncherDone;

    private CountLauncherRefund countLauncherRefund;

    @Override
    public CountLauncherPay getCountLauncherPay() {
        return countLauncherPay;
    }

    @Override
    public void setCountLauncherPay(CountLauncherPay countLauncherPay) {
        this.countLauncherPay = countLauncherPay;
    }

    @Override
    public CountLauncherFail getCountLauncherFail() {
        return countLauncherFail;
    }

    @Override
    public void setCountLauncherFail(CountLauncherFail countLauncherFail) {
        this.countLauncherFail = countLauncherFail;
    }

    @Override
    public CountLauncherSuccess getCountLauncherSuccess() {
        return countLauncherSuccess;
    }

    @Override
    public void setCountLauncherSuccess(CountLauncherSuccess countLauncherSuccess) {
        this.countLauncherSuccess = countLauncherSuccess;
    }

    @Override
    public CountLauncherDone getCountLauncherDone() {
        return countLauncherDone;
    }

    @Override
    public void setCountLauncherDone(CountLauncherDone countLauncherDone) {
        this.countLauncherDone = countLauncherDone;
    }

    @Override
    public CountLauncherRefund getCountLauncherRefund() {
        return countLauncherRefund;
    }


    @Override
    public void setCountLauncherRefund(CountLauncherRefund countLauncherRefund) {
        this.countLauncherRefund = countLauncherRefund;
    }

}
